/* eslint-disable no-undef */
/* eslint-disable no-underscore-dangle */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-continue */
/* eslint-disable no-plusplus */
/* eslint-disable import/extensions */
/* eslint-disable no-invalid-this */
import ElEditable from '@components/el-editable';
import {
  orderCommonSubmitOrder,
  orderCommonSaveOrder,
  queryOrderInfo,
  echoConfirmConsumptionProduct,
  findProductSnInfo
} from '@api/m_mall_web_v1.js';
import { isObject, throttle } from 'lodash';
import upload from '@/components/sales-upload';
import SerialUpload from '@/components/serial-upload';
import { urlDownload } from '@const/utils';
import TableUpload from '~/modules/table-upload';
import { PurchaseProductsListComponent } from '~/components/purchase-order/purchase-products-list/salesorderindex.js';
import { SupplierAndContractComponent } from '~/components/purchase-order/supplier-and-contract/salesorder.js';
import { IndexService } from './index.service';
import * as CONSTS from './index.const';

const indexService = new IndexService();
export default {
  components: {
    ElEditable,
    SupplierAndContractComponent,
    PurchaseProductsListComponent,
    TableUpload,
    upload,
    SerialUpload
  },
  inject: ['apiMMallWeb', 'reload'],
  data() {
    return {
      show: true,
      elLeft: 0,
      elTop: 0,
      showMoveDot: [],
      ...CONSTS,
      active_index: 1,
      step_count: 1, // 仅用于记录是否是第一次进入第三步
      dialogVisible: false,
      submit_loading: false,
      bus_model: '2',
      is_edit: false,
      extend_model: [], // 传给form-render所需要的经过整理的内容
      base_extend_data: [], // 从接口拿到的原始的表单配置数据，提交的时候需要
      stepOneFormData: {},
      titleStr: '批发采购',
      form_data: {
        active_index: this.active_index,
        // id: '',
        // detail_id: '',
        supplier: '',
        contract: '',
        // carryway: '',
        // address: '',
        ordertype: '',
        onsignOrderType: '2',
        payway: '',
        address_full: {},
        // operation: '',
        remark: '',
        extend: {},
        products: [],
        doctor: '',
        saleTargetName: ''
      },
      submit_data: {
        busModel: '2',
        busFunction: '1',
        orderType: '', // 这个不要了，但是前端还要传空
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: '', // 承运方式
        remark: '', // 备注
        orderCode: '', // 订单编码
        orderDetailId: '', // 订单详情id
        orderId: '', // 订单id
        // 第一步供应商
        supplierVo: {
          vendorCode: '',
          vendorName: ''
        },
        contractVo: null, // 第一步-合同
        saveProductVO: null, // 第二步产品
        addressResDto: null, // 第三步-地址
        orderAppendPOS: null // 第三步-附加信息
      },
      readonly_formdata: {
        supplier: '',
        contract: ''
      },
      storageAddress: {},
      thirdExpandVerifyFlag: false, // 把第三步的校验提出来
      isFirstMount: true,
      // 用于提交的页面信息
      page_data: {
        remark: '',
        contract: {},
        create: {
          supplier: '', // 供应商
          contract: '' // 合同
        }, // 创建报台
        sales_info: {
          target: '', // 销售对象
          date: '' // 销售日期
        }, // 销售信息
        sales_products: [], // 销售产品
        other_info: {
          additional: {}, // 附加信息
          invoice: {
            content: []
          }, // 发票信息
          other: {
            content: []
          } // 其他信息
        } // 其他信息
      },
      productsObj: {
        products_arr: []
      },
      toSubmitDialogVisible: false,
      seqNoVoList: [], // 序列号
      reloadSeqNoVoList: true,
      occupy: false
    };
  },
  watch: {
    active_index: {
      handler() {
        document.querySelector('.nuxt-main').scrollTop = 0;
      }
    }
  },
  computed: {
    queryParams() {
      return {
        orderId: this.$route.query.id
      };
    }
  },
  mounted() {
    this.initGlobalBtn();
  },
  beforeRouteUpdate(to, from, next) {
    next();
    this.reload();
  },
  created() {
    // 编辑模式
    if (this.queryParams.orderId) {
      this.$axios({
        url: queryOrderInfo,
        method: 'post',
        data: {
          orderId: this.queryParams.orderId
        }
      }).then(res => {
        const result = res.data.payload ? res.data.payload : {};
        result.transportType = result.transportType
          ? `${result.transportType}`
          : result.transportType;
        // 其实这里直接把结果赋值给submit_data就可以了，但是为了某些更改项的对应，还是重新一一赋值一下。
        this.resetDetailInfo(result);
        this.is_edit = true;
      });
    }
  },
  methods: {
    enter(el, done) {
      const newEl = el;
      // eslint-disable-next-line no-unused-expressions
      newEl.offsetWidth;
      // 获取徽标在页面中的位置
      const badgePosition = document
        .getElementById('appCart')
        .getBoundingClientRect();
      const xDist = badgePosition.left - this.elLeft;
      const yDist = badgePosition.top - this.elTop;
      newEl.style.transform = `translate(${xDist}px, ${yDist}px)`;
      newEl.style.transition = 'all 0.8s cubic-bezier(0.12,0.78,0.53,0.92)';
      this.showMoveDot = this.showMoveDot.map(() => false);
      done();
    },
    // 额外单独获取产品详情
    getProductsList(id) {
      this.$axios({
        url: echoConfirmConsumptionProduct,
        method: 'post',
        data: {
          orderId: id,
          page: 1,
          pageSize: 9999
        }
      }).then(res => {
        const result = res.data.payload.content.length
          ? res.data.payload.content
          : [];
        // 毫无意义的数据转换，为后端各接口返回值不匹配买单
        // result = this.filterProducts(result)
        result.forEach(r => {
          const newR = r;
          newR.oldProductCountNumber = r.productCount || 0;
        });
        this.submit_data.saveProductVO = result;
        this.form_data.products = result;
      });
    },
    /**
     * 编辑时 对返回产品数据进行验证
     * 销售数量大于0的产品 和 可用量为0的产品自动清除
     * 若销售数量大于可用量设置销售数量的值为可用量的值
     */
    filterProducts(resultArr) {
      for (let i = resultArr.length - 1; i >= 0; i--) {
        const item = resultArr[i];
        if (
          item &&
          Number(item.productCount) === 0 &&
          this.active_index === 2
        ) {
          this.occupy = true;
          resultArr.splice(i, 1);
          continue;
        }
        if (
          item &&
          Number(item.availableQuantity) === 0 &&
          this.active_index === 2
        ) {
          this.occupy = true;
          resultArr.splice(i, 1);
          continue;
        }
        if (
          Number(item.oldProductCountNumber) > Number(item.availableQuantity) &&
          Number(item.availableQuantity) > 0 &&
          this.active_index === 2
        ) {
          this.occupy = true;
        }
      }
      return resultArr;
    },
    resetDetailInfo(detail) {
      const newDetail = detail;
      // 最先调用第三步的附加信息，获取其表单框架
      // 先给第二步的详情赋值,其实就是从结果里单独抽出来
      const readOnlyDetail = {
        vendorName: detail.supplierVo.vendorName,
        contract: detail.contractVo.supplierName
      };
      newDetail.contractVo.originalFactoryCode =
        detail.contractVo.supplierCode || '';
      newDetail.contractVo.originalFactoryName =
        detail.contractVo.supplierName || '';
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(
        readOnlyDetail
      );
      // 然后给submit_data赋值，多说一下，submit_data是最后提交的经过整理的内容，而form_data是未经整理的散乱的。
      // 换句话说，submit_data是给后端接口用的，form_data是给前端自己用的。
      this.submit_data = {
        busModel: detail.busModel,
        busFunction: '1',
        orderType: '', // 订单类型
        orderTypeId: detail.orderTypeId,
        payType: detail.payType, // 支付方式
        payUse: detail.payUse, // 支付用途
        transportType: detail.transportType || '', // 承运方式
        remark: detail.remark, // 备注
        orderCode: detail.orderCode, // 订单编码
        orderDetailId: detail.orderDetailId, // 订单详情id
        orderId: detail.orderId, // 订单id
        // 第一步供应商
        supplierVo: detail.supplierVo,
        contractVo: detail.contractVo, // 第一步-合同
        addressResDto: detail.addressResDto, // 第三步-地址
        orderAppendPOS: detail.orderAppendPOS // 第三步-附加信息
      };
      // 还要给前端数据form_data赋值
      this.form_data = {
        products: [],
        active_index: this.active_index,
        detail_id: this.submit_data.orderDetailId,
        supplier: this.submit_data.supplierVo.vendorCode,
        contract: `${this.submit_data.contractVo.supplierCode || ''}${this
          .submit_data.contractVo.productLineCode || ''}${this.submit_data
          .contractVo.vendorCode || ''}${this.submit_data.contractVo
          .marketCode || ''}`,
        // carryway: this.submit_data.transportType || '',
        // address: this.submit_data.addressResDto.userAddressId || '',
        ordertype: this.submit_data.orderTypeId,
        onsignOrderType: '2',
        payway: this.submit_data.payType,
        address_full: this.submit_data.addressResDto,
        remark: this.submit_data.remark
      };
      const obj = {};
      this.submit_data.orderAppendPOS.forEach(item => {
        obj[item.attributeNameValue] = item.attributeValue;
      });
      this.form_data.extend = obj;
      // 回显附件信息
      const commonFilePOListLength = detail.commonFilePOList.length;
      for (let i = 0; i < commonFilePOListLength; i++) {
        const f = detail.commonFilePOList[i];
        const item = {};
        item.fileUrl = f.fileUrl;
        item.fileName = f.fileName;
        item.fileType = f.fileUrl.substring(f.fileUrl.lastIndexOf('.') + 1);
        this.$set(this.page_data.other_info.other.content, i, item);
      }
      // this.page_data.other_info.other = detail.commonFilePOList
      // 额外获取第二步的产品数据，orderDetailId不从路由拿去，只从这个详情数据中取。
      // 路由实际参数只有orderId是有用的
      this.getProductsList(this.submit_data.orderId);
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      const prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      const nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      if (this.active_index !== 1) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 3) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      if (this.active_index !== 1) {
        btnObj.arr.push(saveDraftBtn);
      }
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    showConfirmDialog() {
      let salesPerson = false;
      this.$refs.expandFormRenderer.validate(valid => {
        salesPerson = true;
        // eslint-disable-next-line no-empty
        if (valid) {
        } else {
          salesPerson = false;
        }
      });

      const formDatas = {
        seqNoVoList: this.seqNoVoList,
        form_data: this.form_data,
        page_data: this.page_data,
        submit_data: this.submit_data,
        extend_model: this.extend_model,
        salesPerson
      };
      const verifyResult = indexService.verifyStep(3, formDatas);
      if (verifyResult.pass === true) {
        this.$refs.expandFormRenderer.validate(valid => {
          if (valid) {
            this.dialogVisible = true;
            this.saveTheData();
          } else {
            this.$message({
              message: '您所填写的附加信息有误，请确认后重新填写填',
              type: 'warning'
            });
          }
        });
      } else if (verifyResult.message === '请添加附件') {
        this.$notify({
          message: verifyResult.message,
          type: 'warning'
        });
      } else {
        this.$notify({
          title: '必填项',
          message: verifyResult.message,
          type: 'warning'
        });
      }
    },
    onSubmit: throttle(
      // eslint-disable-next-line func-names
      function() {
        if (this.submit_data.transportType === '1') {
          this.submit_data.addressResDto = {};
        } else {
          this.submit_data.addressResDto = this.storageAddress;
        }
        // eslint-disable-next-line consistent-return
        this.$refs.expandFormRenderer.validate(valid => {
          if (valid) {
            // alert('submit!');
          } else {
            return false;
          }
        });
        this.submit_loading = true;
        this.$axios({
          url: orderCommonSubmitOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            if (res.data.code === '0') {
              // this.$router.push('/purchase-order/salesorder/list');
              this.toSubmitDialogVisible = true;
              // this.$message({
              //   message: '订单提交成功',
              //   type: 'success'
              // });
            }
          })
          .catch(err => {
            if (err.data.code === '200001') {
              this.$router.push('/purchase-order/salesorder/list');
            }
          })
          .finally(() => {
            this.dialogVisible = false;
            this.submit_loading = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onNext() {
      if (
        this.queryParams.orderId &&
        this.active_index >= 2 &&
        this.reloadSeqNoVoList
      ) {
        this.findProductSnInfo();
      }
      let salesPerson = false;
      this.$refs.expandFormRenderer.validate(valid => {
        salesPerson = true;
        // eslint-disable-next-line no-empty
        if (valid) {
        } else {
          salesPerson = false;
        }
      });
      const formDatas = {
        seqNoVoList: this.seqNoVoList,
        form_data: this.form_data,
        page_data: this.page_data,
        submit_data: this.submit_data,
        extend_model: this.extend_model,
        salesPerson
      };
      this.step_count++;
      const verifyResult = indexService.verifyStep(
        this.active_index,
        formDatas
      );
      if (verifyResult.pass === true) {
        if (this.active_index++ >= 3) this.active_index = 3;
        if (this.active_index === 2) {
          this.filterProducts(this.form_data.products);
        }
        this.setExpandData();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
      this.initGlobalBtn();
    },
    onPrev() {
      this.step_count++;
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    contractChangeChangedatas(val) {
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(val);
      this.submit_data.supplierVo = Object.assign(
        this.submit_data.supplierVo || {},
        val.suppliy
      );
      this.submit_data.contractVo = Object.assign(
        this.submit_data.contractVo || {},
        val.contract
      );
      this.submit_data.busModel = this.submit_data.contractVo.businessModelCode;
      this.form_data.suppliy = val.vendorCode || '';
      // 这里要清空一些特殊的数据
      // 第2步的产品列表和第三步的订单类型
    },
    onSupplierAndContractChange(val) {
      this.removeSeqNoVoListFn(val);
      this.readonly_formdata = indexService.mappingOrderDetailReadonly(val);
      this.submit_data.supplierVo = Object.assign(
        this.submit_data.supplierVo || {},
        val.suppliy
      );
      this.submit_data.contractVo = Object.assign(
        this.submit_data.contractVo || {},
        val.contract
      );
      this.submit_data.busModel = this.submit_data.contractVo.businessModelCode;
      this.form_data.suppliy = val.vendorCode || '';
      this.submit_data.contractVo.supplierName = this.submit_data.contractVo.vendorName;
      this.submit_data.contractVo.supplierCode = this.submit_data.contractVo.vendorCode;
      // 这里要清空一些特殊的数据
      // 第2步的产品列表和第三步的订单类型
      if (!this.isFirstMount) {
        if (this.form_data.products.length) {
          this.submit_data.saveProductVO = null;
          this.form_data.products = [];
        }

        if (this.form_data.ordertype) {
          this.form_data.ordertype = '';
          if (this.submit_data.orderTypeId) this.submit_data.orderTypeId = '';
        }
      }
    },
    onAddressChanged(val) {
      // 地址需要全量数据
      this.form_data.address_full = val;
      this.submit_data.addressResDto = Object.assign(
        this.submit_data.addressResDto || {},
        val
      );
      this.storageAddress = this.submit_data.addressResDto;
    },
    saveTheData() {
      // 通过sync和update更新products数据，所以这里要赋值以下，该操作意图等同于onSupplierAndContractChange方法。
      // 赋值第二步选择产品部分数据
      this.form_data.products.forEach(p => {
        const newP = p;
        if (p.productPrice === '待定') {
          newP.productPrice = null;
        }
        newP.originalProductCode = newP.originalFactoryProductCode;
        newP.referencePrice = newP.productPrice;
        newP.attribute1 = newP.model;
        newP.originalFactoryCode =
          this.submit_data.contractVo.vendorCode ||
          this.submit_data.contractVo.supplierCode;
        newP.originalFactoryName =
          newP.manufacturerName ||
          this.submit_data.contractVo.vendorName ||
          this.submit_data.contractVo.supplierName;
      });
      this.submit_data.saveProductVO = this.form_data.products;
      // 复制第三步的三个选项部分（订单类型，承运方式，支付方式，以及备注）
      this.submit_data.orderTypeId = this.form_data.ordertype; // 订单类型
      this.submit_data.orderType = '';
      // this.submit_data.transportType = this.form_data.carryway; // 承运方式
      this.submit_data.payType = this.form_data.payway; // 支付方式
      this.submit_data.remark = this.form_data.remark; // 备注

      // 这里，要把expand动态生成的表单，组合成后端想要的数据格式，也就是说，要再反向重组一下。
      const extendResult = this.base_extend_data;
      extendResult.forEach(item => {
        const newItem = item;
        if (item && item.attributeNameValue) {
          newItem.attributeValue =
            this.form_data.extend[item.attributeNameValue] || '';
          delete newItem.valueRange;
        }
      });
      this.submit_data.orderAppendPOS = extendResult;
      if (this.submit_data.transportType === '1') {
        this.submit_data.addressResDto = {};
      } else {
        this.submit_data.addressResDto = this.storageAddress;
      }
    },
    splitSubmitDataBySteps() {
      const curStep = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      let splitSubmitData = {
        busModel: '',
        busFunction: '1',
        orderType: '', // 订单类型
        orderTypeId: '', // 订单类型
        payType: '', // 支付方式
        payUse: '', // 支付用途
        transportType: '', // 承运方式
        remark: '', // 备注
        orderCode: this.submit_data.orderCode, // 订单编码
        orderDetailId: this.submit_data.orderDetailId, // 订单详情id
        orderId: this.submit_data.orderId, // 订单id
        // 第一步供应商
        supplierVo: {
          vendorCode: '',
          vendorName: ''
        },
        contractVo: null, // 第一步-合同
        saveProductVO: null, // 第二步产品
        addressResDto: null, // 第三步-地址
        orderAppendPOS: null // 第三步-附加信息
      };
      // 第一步
      // eslint-disable-next-line default-case
      switch (curStep) {
        // 第一步，只存第一步的合同和供应商
        case 1:
          splitSubmitData.supplierVo = this.submit_data.supplierVo;
          splitSubmitData.contractVo = this.submit_data.contractVo;
          splitSubmitData.busModel = this.submit_data.busModel;
          break;
        // 除了第一步的，还额外需要产品部分
        case 2:
          splitSubmitData.supplierVo = this.submit_data.supplierVo;
          splitSubmitData.contractVo = this.submit_data.contractVo;
          splitSubmitData.saveProductVO = this.submit_data.saveProductVO;
          this.submit_data.busModel = 11;
          splitSubmitData.busModel = 11;
          this.submit_data.commonFileForms = this.page_data.other_info.other.content;
          this.submit_data.saleTargetName = this.form_data.saleTargetName;
          this.submit_data.doctor = this.form_data.doctor;
          this.submit_data.productSnList = this.seqNoVoList;
          splitSubmitData = this.submit_data;
          this.submit_data.orderType = '';
          this.submit_data.orderTypeId = '';
          break;
        // 第三步就比较简单了
        case 3:
          this.submit_data.commonFileForms = this.page_data.other_info.other.content;
          this.submit_data.saleTargetName = this.form_data.saleTargetName;
          this.submit_data.doctor = this.form_data.doctor;
          this.submit_data.busModel = 11;
          this.submit_data.productSnList = this.seqNoVoList;
          splitSubmitData = this.submit_data;
          this.submit_data.orderType = '';
          this.submit_data.orderTypeId = '';
          break;
      }
      return splitSubmitData;
    },
    saveProgress: throttle(
      // eslint-disable-next-line func-names
      function() {
        this.saveTheData();
        this.$axios({
          url: orderCommonSaveOrder,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            const order = isObject(res.data.payload) ? res.data.payload : {};
            this.submit_data.orderId = order.orderId;
            this.submit_data.orderDetailId = order.orderDetailId;
            this.submit_data.orderCode = order.orderCode;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    async onSaveDraft() {
      // eslint-disable-next-line no-unused-vars
      let salesPerson = false;
      this.$refs.expandFormRenderer.validate(valid => {
        salesPerson = true;
        // eslint-disable-next-line no-empty
        if (valid) {
        } else {
          salesPerson = false;
        }
      });

      // const formDatas = {
      //   seqNoVoList: this.seqNoVoList,
      //   form_data: this.form_data,
      //   page_data: this.page_data,
      //   submit_data: this.submit_data,
      //   extend_model: this.extend_model,
      //   salesPerson
      // }
      this.saveProgress();
      // 如果不是第三步，直接暂存，如果到了第三步，那么需要校验表单后并且通过后，再暂存
      if (this.active_index === 3) {
        this.$refs.expandFormRenderer.validate(valid => {
          if (valid) {
            this.saveProgress();
          }
          // else {
          //   this.$message({
          //     message: '您所填写的附加信息有误，请确认后重新填写填',
          //     type: 'warning'
          //   });
          // }
        });
      } else {
        this.saveProgress();
      }
    },
    verifyCurFileItemDataComplete(type) {
      // let curData;
      // let len;
      const len = this.page_data.other_info[type].content.length;
      if (len === 0) {
        return true;
      }
      const curData = this.page_data.other_info[type].content[0];
      const values = Object.values(curData);
      const flag = values.every(item => !!item);
      return flag;
    },
    // 增加一行其他附件
    addOtherFileItem() {
      // 其实这里可以把验证逻辑再解藕，不过也都还好
      // 独立验证一下长度
      const maxLen = this.page_data.other_info.other.content.length;
      if (maxLen >= 50) {
        this.$message({
          type: 'warning',
          message: '其他附件最多可以添加50行！'
        });
        return;
      }
      // 验证如果当前行没有添加文件，则不允许再加一行
      if (!this.verifyCurFileItemDataComplete('other')) {
        this.$message({
          type: 'warning',
          message: '请将信息填写完整后再添加'
        });
        return;
      }
      const staticOtherItemData = {
        fileName: '', // 文件名	string
        fileType: '', // 文件后缀名：JPG、PDF等	string
        fileUrl: '' // 文件url	string
      };
      this.page_data.other_info.other.content.unshift(staticOtherItemData);
    },
    // 其他附件地址回调
    returnOtherFileUrl(url, index, name) {
      this.page_data.other_info.other.content[index].fileUrl = url;
      this.page_data.other_info.other.content[index].fileName = name.split(
        '.'
      )[0];
      this.page_data.other_info.other.content[index].fileType = name.split(
        '.'
      )[1];
    },
    // 删除一行其他附件
    removeCurOtherItem(scope) {
      this.$confirm('确定要删除该附件文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.page_data.other_info.other.content.splice(scope.$index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    importProduct() {
      this.productsObj.products_arr = [];
      this.$refs.upload.dialog_visible = true;
      (this.form_data.products || []).forEach(p => {
        const item = {};
        item.productCode = p.productCode;
        item.originalFactoryProductCode = p.originalFactoryProductCode;
        item.batchNo = p.batchNo;
        item.productCount = p.productCount;
        item.productName = p.productName;
        this.productsObj.products_arr.push(item);
      });
    },
    // 导入产品序列号
    onOpenImportProduct() {
      if (this.seqNoVoList.length > 0) {
        this.$confirm('确定模板导入，将清空列表已添加的序列号??', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.importProduct();
          })
          .catch(() => {
            // eslint-disable-next-line no-unused-expressions
            this.productsObj.products_arr;
            this.$message({
              type: 'info',
              message: '已取消导入'
            });
          });
      } else {
        this.importProduct();
      }
    },
    onGetProductTemplate() {
      urlDownload(
        'https://mt.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/uvjvtywu6mxg5enw2lftl2r41uurk4bu.xlsx'
      );
    },
    getUploadProducts(payload) {
      const loadProductList = payload;
      if (loadProductList.length > 0) {
        this.updateProductData(payload, true);
      }
    },
    getSeqNoVoList(payload) {
      this.seqNoVoList = payload || [];
    },
    // 删除序列号
    removeSeqNo(scope) {
      this.seqNoVoList.splice(scope.$index, 1);
    },
    onOpenProductDialog() {
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      this.productAddDialogService
        .create({
          title: '添加销售产品',
          query: {
            operationType: this.operationType,
            formData: this.stepOneFormData
          },
          confirmButtonClickHandler: (data = {}) => {
            data.forEach(element => {
              this.$set(element, 'productCount', 1);
            });
            this.updateProductData(data);
          }
        })
        .mount();
    },
    updateProductData(data, isImport) {
      this._products = service.reConcatSelectData(
        data,
        this._products,
        'productCode',
        isImport
      );
      const startIndex = (this.pager.number - 1) * this.pager.size;
      const endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(
        this._products,
        this.pager,
        startIndex,
        endIndex
      );
      this.$emit('update:products', this._products);
    },
    konw() {
      this.$router.push({ path: '/purchase-order/consign/list' });
    },
    occupyKonw() {
      this.occupy = false;
    },
    async setExpandData() {
      // 这里为什么在第三步才能调用，因为要依赖于第一步的数据作为接口获取的入参。
      // 所以无法在创建时就调用该方法
      if (this.active_index === 3) {
        this.base_extend_data = await this.apiMMallWeb.GetAppendInfoOrderV1ApiPOST(
          {
            query: {
              busModel: 11,
              ddbm: 'LCONSIGN_ISSUE',
              productLineCode: this.submit_data.contractVo.productLineCode,
              vendorNum:
                this.submit_data.contractVo.vendorCode ||
                this.submit_data.contractVo.supplierCode,
              page: 1,
              pageSize: 9999
            }
          }
        );
        this.extend_model = indexService.getFormContent(
          this.base_extend_data,
          this.ATTRIBUTE_TYPE_OPTIONS
        );
        // 获取默认值
        const defaultValue = {};
        this.base_extend_data.forEach(item => {
          if (item && item.attributeNameValue) {
            defaultValue[item.attributeNameValue] = item.defaultValue;
          }
        });
        // 这块逻辑有点烦，因为所有的情况都汇聚到这了。
        // 首先数据有默认值，详情反显值和编辑值三种情况。
        // 除了第一次进入第三步，且非编辑模式时，使用默认值，其他情况都使用编辑值。
        // 注意：反显值，在反显数据获取时，赋值给编辑值了。
        // 导致该复杂逻辑的原因：1、需求，2、业务揉合。
        let finalValue;
        if (this.step_count === 3 && !this.is_edit) {
          finalValue = defaultValue;
          // 给编辑值附上初始值，仅第三次且非编辑模式时赋值
          // 为了如果没修改内容，下次进来还是初始值
          this.form_data.extend = defaultValue;
        } else {
          finalValue = this.form_data.extend;
        }

        this.$nextTick(() => {
          this.$refs.expandFormRenderer.updateForm(finalValue);
        });
      }
    },
    // 替换产品列表
    repliceProductFn() {
      this.form_data.products = [];
    },
    // 清空序列号列表
    removeSeqNoVoListFn(val) {
      this.reloadSeqNoVoList = val;
      if (this.seqNoVoList.length > 0) {
        this.seqNoVoList = [];
      }
    },
    // 获取序列号
    findProductSnInfo() {
      this.$axios
        .$post(findProductSnInfo, {
          orderCode: this.submit_data.orderCode,
          page: 0,
          pageSize: 10000
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            (res.payload.content || []).forEach(s => {
              const newS = s;
              newS.originalFactoryProductCode = newS.originalProductCode;
              newS.seqNo = newS.snCode || '';
            });
            this.seqNoVoList = res.payload.content || [];
          }
        });
    }
  }
};
